package com.ljx.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljx.Domain.R;
import com.ljx.Domain.User;
import com.ljx.Service.UserService;
import com.ljx.Utils.SMSUtils;
import com.ljx.Utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService ;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 通过阿里云发送短信
     * @param user
     */
    @PostMapping("sendMsg")
    public R<String> sent(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if(phone!=null){

            //生成4位数验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //通过阿里云发送短信
//            SMSUtils.sendMessage("瑞吉外卖","SMS_154950909",phone,code);
            log.info("验证码:{}",code);
            //将手机号和验证码保存到session
//            session.setAttribute(phone,code);
            //将手机号保存到redis,设置5分钟自动删除
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("发送短信成功");
        }
        return R.error("发送短信失败");
    }
    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取前台验证码
        String code = map.get("code").toString();
        //判断是否与session中的验证码一致
//        Object codeInSession = session.getAttribute(phone);
        //从redis中取出验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        if(codeInSession!=null&&codeInSession.equals(code)){
            //相同，判断是否是新用户
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if(user==null){
                //是，自动补全用户信息
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //登录成功
            //删除redis中的验证码
            redisTemplate.delete(phone);
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
    return R.error("验证码错误");
    }
}
